<template>
  <view :class="['lys-img-lazy', `${imgId}`]" :id="imgId">
    <image :src="imgLoad ? imgSrc : ''" :mode="imgMode"></image>
  </view>
</template>
<script>
export default {
  name: 'lys-img-lazy',
  props: {
    imgSrc: {
      type: String || null,
      default: ''
    },
    imgMode: {
      type: String || null,
      default: 'widthFix'
    }
  },
  data() {
    return {
      imgId: 'lys-img-lazy_' + parseInt(Math.random() * 1000000000),
      imgLoad: false
    };
  },
  mounted() {
    let that = this;

    // #ifdef H5
    let observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          that.imgLoad = true;
          observer.disconnect();
        }
      });
    });
    observer.observe(document.querySelector(`.${this.imgId}`));
    // #endif

    // #ifndef H5
    this.intersectionObserverFun(that);
    // #endif
  },
  methods: {
    intersectionObserverFun(that) {
      this.$nextTick(() => {
        let imgLazy = uni.createIntersectionObserver(that);
        imgLazy
          .relativeToViewport({
            bottom: 20
          })
          .observe(`.${this.imgId}`, (result) => {
            that.imgLoad = true;
            imgLazy.disconnect();
          });
      });
    }
  }
};
</script>
<style scoped lang="scss">
.lys-img-lazy {
  display: flex;
  align-items: center;
  justify-content: center;

  image {
    width: 100%;
  }
}
</style>
